<!--
 * @Descripttion: 工单管理-工单详情
 * @Author: 马义超 yichao@ssc-hn.com
 * @Date: 2024-06-07
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-07-08
-->
<template>
  <div class="workOrder-position-list">
    <div class="work-header">
      <arrow-left-outlined :style="{ 'font-weight': 'bold', 'margin-right': '18px' }" @click="router.back()" />
      <span>工单详情</span>
    </div>
    <a-divider />
    <a-row>
      <a-col :span="8">
        <a-form-item label="工单编号">{{ detailData.id }}</a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="发起用户">{{ detailData.createName }}</a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="工单类型">{{ detailData.worksheetType === 1 ? '业务开发类' : detailData.worksheetType === 2 ? '基础OA类' : '' }}</a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="发起时间">{{ detailData.createTime || '--' }}</a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="业务范围">{{ detailData.businessScope }}</a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="工单状态">{{ worksheetRecordState === '1' ? '审核中' : worksheetRecordState === '2' ? '已通过' : '已驳回' }}</a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="8" v-for="item in detailData.formData" :key="item.questionName">
        <a-form-item :label="item?.questionName">
          <template v-if="Array.isArray(item?.value)">
            <a class="view-link" :title="aItem.response.responseData" v-for="aItem in item.value" :key="aItem.uid" @click="openView(aItem.response.responseData)">{{ aItem.response.responseData.substring(aItem.response.responseData.lastIndexOf('/') + 1) }}</a>
          </template>
          <template v-else>{{ item?.value }}</template>
        </a-form-item>
      </a-col>
    </a-row>
    <a-table tableLayout="fixed" class="record-table" :columns="columns" :data-source="detailData.recordData" />
    <a-modal v-model:visible="modalData.visible" title="工单审批" @ok="approveOrder" @cancel="cancelModal">
      <a-form layout="vertical" :model="modalData" ref="formRef">
        <a-form-item :label="`${modalData.type ? '通过' : '驳回'}意见`" :rules="[{ required: true, message: `请填写审批意见` }]">
          <a-textarea :rows="3" v-model:value="modalData.content" allow-clear showCount :maxlength="200" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
    <div class="commit-area">
      <a-button v-if="worksheetRecordState === '1'" type="primary" danger @click="showApprove(false)">驳回</a-button>
      <a-button v-if="worksheetRecordState === '1'" type="primary" @click="showApprove(true)">审核通过</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ArrowLeftOutlined } from '@ant-design/icons-vue'
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  const route = useRoute()
  const formRef = ref()
  const { worksheetRecordId, taskId, worksheetRecordState, createBy } = route.query

  import { message } from 'ant-design-vue'

  import { requestApproveInfo, requestPassTask, requestRejectTask } from '/@/api/business/worksheet'
  import { requestPaperAndQuestions, requestPaperDetail } from '/@/api/content/survey/unAuth/api/json/app/config'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { formatToDateTime } from '/@/utils/date'

  const detailData = reactive<any>({
    id: null,
    worksheetType: null,
    createTime: null,
    businessScope: null,
    recordData: [],
    createName: null,
    formData: [],
  })
  const modalData = reactive({
    visible: false,
    content: null,
    type: null,
  })
  const columns = [
    { title: '审批人', dataIndex: 'approveName' },
    { title: '审批意见', dataIndex: 'approveOpinion', width: 500 },
    { title: '审批结果', dataIndex: 'approveResult' },
    { title: '审批时间', dataIndex: 'approveTime' },
  ]
  const resultState = {
    '-1': '审核拒绝',
    '0': '审核完成',
    '1': '待审核',
  }
  const router = useRouter()

  const openView = (url) => {
    window.open(url)
  }
  const initDetail = async () => {
    const { responseCode, responseData } = await requestApproveInfo({ worksheetRecordId: worksheetRecordId as string, taskId: taskId as string })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      const { worksheetRecordId, worksheetType, createTime, businessScope, recordList, createName, paperId, recordId } = responseData
      detailData.createTime = createTime ? formatToDateTime(createTime) : null
      detailData.id = worksheetRecordId
      detailData.worksheetType = worksheetType
      detailData.businessScope = businessScope
      detailData.recordData = recordList.map((item) => {
        return { ...item, approveTime: formatToDateTime(item.approveTime), approveResult: resultState[item.approveResult] }
      })
      detailData.createName = createName
      initTemplateInfo(paperId, recordId)
    }
  }

  const stripHtmlTags = (htmlString) => {
    // 创建一个临时的DOM元素
    const tempDiv = document.createElement('div')
    // 将HTML字符串设置为元素的内容
    tempDiv.innerHTML = htmlString
    // 使用textContent属性获取纯文本内容
    return tempDiv.textContent || tempDiv.innerText || ''
  }

  const getTextById = (id, dataArray) => {
    // 在数组中查找匹配的对象
    let foundItem = dataArray.find(function (item) {
      return item.questionId === id
    })
    console.log(foundItem)
    // 如果找到匹配的对象，则返回其text值，否则返回空字符串
    return foundItem?.value?.file ? foundItem.value?.file : foundItem?.value?.text
  }

  const initTemplateInfo = async (paperId, recordId) => {
    const userId = createBy as string
    Promise.all([requestPaperDetail({ recordId, userId }), requestPaperAndQuestions({ paperId })]).then(([paperResult, tempResult]) => {
      console.log(paperResult, tempResult)
      if (paperResult.responseCode === HttpCodeEnum.SUCCESS && tempResult.responseCode === HttpCodeEnum.SUCCESS) {
        const paperData = paperResult.responseData
        const tempData = tempResult.responseData
        const { questions } = tempData
        if (questions) {
          const answerData = paperData?.answerText ? JSON.parse(paperData.answerText) : []
          const tempList = questions.map((item) => {
            return {
              questionName: stripHtmlTags(item.questionName),
              value: getTextById(item.questionId, answerData),
            }
          })
          detailData.formData = tempList
        }
      }
    })
  }

  const showApprove = (res) => {
    modalData.type = res
    modalData.visible = true
  }

  const cancelModal = () => {
    modalData.content = null
  }

  const approveOrder = async () => {
    formRef.value.validate().then(async () => {
      const params = { worksheetRecordId: worksheetRecordId as string, taskId: taskId as string, formList: [{ formId: '1', fieldKey: 'approvalOpinions', fieldValue: modalData.content }] }
      const action = modalData.type ? requestPassTask(params) : requestRejectTask(params)
      const { responseCode } = await action
      if (responseCode === HttpCodeEnum.SUCCESS) {
        modalData.type ? message.success('工单通过') : message.success('工单驳回')
        modalData.visible = false
        router.back()
      }
    })
  }

  onMounted(() => {
    if (worksheetRecordId) initDetail()
  })
</script>

<style lang="less" scoped>
  .workOrder-position-list {
    background: #fff;
    padding: 24px;
    min-height: 100%;

    .work-header {
      font-size: 18px;
      font-weight: 500;
      color: #000;
    }

    .record-table {
      width: calc(100vw - 600px);
      margin: 15px 0;
    }

    .view-link {
      max-width: 420px;
      display: inline-block;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    .commit-area {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-top: 20px;

      .ant-btn {
        & + * {
          margin-left: 8px;
        }
      }
    }
  }
</style>
